# coding:utf-8


class Solution:
    def myAtoi(self, s: str) -> int:
        ans = 0
        negivate = False
        first_sign = True # 出现的第一个符号
        first_not_null = True # 出现的第一个非空字符 + - 0-9
        # pre_zero = True # 前导0
        for ch in s:
            if ch==' ' and first_not_null:
                continue
            # elif ch=='0' and pre_zero:
            #     continue
            elif ch=='-' and first_sign:
                negivate = True
                first_sign = False
                first_not_null = False
            elif ch=='+' and first_sign:
                first_sign = False
                first_not_null = False
            elif ch>='0' and ch<='9' and first_not_null:
                first_not_null = False
                first_sign = False
                # pre_zero = False
                ans = int(ch)
            elif ch>='0' and ch<='9':
                ans = ans*10 + int(ch)
            else:
                break

        if negivate:
            return min(2**31,ans)*-1
        else:
            return min(2**31-1,ans)

if __name__ == "__main__":
    solu = Solution()
    print(solu.myAtoi("   +0 123"))
